const express = require("express")
const http = require("http")
const ioServer = require("socket.io")
const jwt = require("jsonwebtoken")
const {expressjwt} = require("express-jwt")


const api = require("./routes/api")
const {jwtBlackList} = require("./utils/consts")

const app = express()
const server = http.createServer(app)
const io = ioServer(server)

app.set("io",io)

io.on("connection",socket=>{
    console.log(socket.id);
    
})



app.use(express.static("public"))
app.use(express.json())


// Verify JWT
app.use(
  expressjwt({
    secret: process.env.SECRET,
    algorithms: ["HS256"],
    isRevoked: (req,token)=>{
        //jwtBlackList.tidy()
        return jwtBlackList.has(req.header("Authorization")?.split(" ")[1])
    }
  }).unless({ path: ["/api/v1/login","/api/v1/register"] })
)

// Handle JWT 401 Error
app.use((err,req,res,next)=>{
    if(err.status===401){
        return res.status(401).json({
            msg: "unauthorized"
        })
    }
    next(err)
})

app.use("/api/v1",api)

const PORT = process.env.PORT || 3000

server.listen(PORT, ()=>{
    console.log(`Server started on port ${PORT}...`)
})

